/**
 * 邮箱
 * @param {*} s
 */
export function isEmail(s) {
  return /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((.[a-zA-Z0-9_-]{2,3}){1,2})$/.test(s)
}

/**
 * 手机号码
 * @param {*} s
 */
export function isMobile(s) {
  // return /^1[0-9]{10}$/.test(s)
  return /[1][3,4,5,6,7,8,9][0-9]{9}$/.test(s)
}

/**
 * 电话号码
 * @param {*} s
 */
export function isPhone(s) {
  return /^([0-9]{3,4}-)?[0-9]{7,8}$/.test(s)
}

/**
 * URL地址
 * @param {*} s
 */
export function isURL(s) {
  return /^http[s]?:\/\/.*/.test(s)
}

/* 合法uri */
export function validateURL(textval) {
  const urlregex = /^(https?|ftp):\/\/([a-zA-Z0-9.-]+(:[a-zA-Z0-9.&%$-]+)*@)*((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]?)(\.(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}|([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(:[0-9]+)*(\/($|[a-zA-Z0-9.,?'\\+&%$#=~_-]+))*$/
  return urlregex.test(textval)
}

/* 小写字母 */
export function validateLowerCase(str) {
  const reg = /^[a-z]+$/
  return reg.test(str)
}

/* 大写字母 */
export function validateUpperCase(str) {
  const reg = /^[A-Z]+$/
  return reg.test(str)
}

/* 大小写字母 */
export function validatAlphabets(str) {
  const reg = /^[A-Za-z]+$/
  return reg.test(str)
}

/* 验证pad还是pc */
export const vaildatePc = function() {
  const userAgentInfo = navigator.userAgent
  const Agents = ['Android', 'iPhone',
    'SymbianOS', 'Windows Phone',
    'iPad', 'iPod'
  ]
  let flag = true
  for (let v = 0; v < Agents.length; v++) {
    if (userAgentInfo.indexOf(Agents[v]) > 0) {
      flag = false
      break
    }
  }
  return flag
}

/**
 * validate email
 * @param email
 * @returns {boolean}
 */
export function validateEmail(email) {
  const re = /^(([^<>()\\[\]\\.,;:\s@"]+(\.[^<>()\\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
  return re.test(email)
}

/**
 * 判断身份证号码
 * //身份证号合法性验证
 //支持15位和18位身份证号
 //支持地址编码、出生日期、校验位验证
 */
export function validateIdCard(idCard) {
  const vcity = {
    11: '北京', 12: '天津', 13: '河北', 14: '山西', 15: '内蒙古',
    21: '辽宁', 22: '吉林', 23: '黑龙江', 31: '上海', 32: '江苏',
    33: '浙江', 34: '安徽', 35: '福建', 36: '江西', 37: '山东', 41: '河南',
    42: '湖北', 43: '湖南', 44: '广东', 45: '广西', 46: '海南', 50: '重庆',
    51: '四川', 52: '贵州', 53: '云南', 54: '西藏', 61: '陕西', 62: '甘肃',
    63: '青海', 64: '宁夏', 65: '新疆', 71: '台湾', 81: '香港', 82: '澳门', 91: '国外'
  }

  // 判断是否为空
  const isEmpty = function(card) {
    if (/^\s*$/.test(card) === true) {
      return true
    }
  }
  //检查号码是否符合规范，包括长度，类型
  const isCardNo = function(card) {
    if (isEmpty(card)) {
      return true
    }
    //这个代码表示身份证可以为空
    //身份证号码为15位或者18位，15位时全为数字，18位前17位为数字，最后一位是校验位，可能为数字或字符X
    const reg = /(^\d{15}$)|(^\d{17}(\d|X)$)/
    if (reg.test(card) === false) {
      return false
    }


    return true
  }

  //取身份证前两位,校验省份
  const checkProvince = function(card) {
    if (isEmpty(card)) {
      return true
    }
    const province = card.substr(0, 2)
    if (typeof vcity[province] === 'undefined') {
      return false
    }
    return true
  }

  //检查生日是否正确
  const checkBirthday = function(card) {
    if (isEmpty(card)) {
      return true
    }
    const len = card.length
    //身份证15位时，次序为省（3位）市（3位）年（2位）月（2位）日（2位）校验位（3位），皆为数字
    if (len === 15) {
      const re_fifteen = /^(\d{6})(\d{2})(\d{2})(\d{2})(\d{3})$/
      const arr_data = card.match(re_fifteen)
      const year = arr_data[2]
      const month = arr_data[3]
      const day = arr_data[4]
      const birthday = new Date('19' + year + '/' + month + '/' + day)
      return verifyBirthday('19' + year, month, day, birthday)
    }
    //身份证18位时，次序为省（3位）市（3位）年（4位）月（2位）日（2位）校验位（4位），校验位末尾可能为X
    if (len === 18) {
      const re_eighteen = /^(\d{6})(\d{4})(\d{2})(\d{2})(\d{3})([0-9]|X)$/
      const arr_data = card.match(re_eighteen)
      const year = arr_data[2]
      const month = arr_data[3]
      const day = arr_data[4]
      const birthday = new Date(year + '/' + month + '/' + day)
      return verifyBirthday(year, month, day, birthday)
    }
    return false
  }

  //校验日期
  const verifyBirthday = function(year, month, day, birthday) {
    const now = new Date()
    const now_year = now.getFullYear()

    //年月日是否合理
    const time = now_year - year
    if (time >= 3 && time <= 100) {
      return true
    }
    return false
  }

  //校验位的检测
  const checkParity = function(card) {
    if (isEmpty(card)) {
      return true
    }
    //15位转18位
    card = change15To18(card)
    const len = card.length
    if (len === 18) {
      const arrInt = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
      const arrCh = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2']
      let cardTemp = 0, i, valnum
      for (i = 0; i < 17; i++) {
        cardTemp += card.substr(i, 1) * arrInt[i]
      }
      valnum = arrCh[cardTemp % 11]
      if (valnum === card.substr(17, 1)) {
        return true
      }
      return false
    }
    return false
  }

  //15位转18位身份证号
  const change15To18 = function(card) {
    if (isEmpty(card)) {
      return true
    }
    if (card.length === 15) {
      const arrInt = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
      const arrCh = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2']
      let cardTemp = 0, i
      card = card.substr(0, 6) + '19' + card.substr(6, card.length - 6)
      for (i = 0; i < 17; i++) {
        cardTemp += card.substr(i, 1) * arrInt[i]
      }
      card += arrCh[cardTemp % 11]
      return card
    }
    return card
  }
  idCard = idCard.toUpperCase()
  //校验长度，类型
  if (isCardNo(idCard) === false) {
    //alert('您输入的身份证号码不正确，请重新输入');
    //document.getElementById('card_no').focus;
    //console.log('isCardNo false')
    return false
  }
  //检查省份
  if (checkProvince(idCard) === false) {
    //console.log('checkProvince false')
    return false
  }
  //校验生日
  if (checkBirthday(idCard) === false) {
    //console.log('checkBirthday false')
    return false
  }
  //检验位的检测
  if (checkParity(idCard) === false) {
    //console.log('checkParity false')
    return false
  }

  return true
}

/**
 * 校验 统一社会信用代码
 * @param Code
 * @returns {boolean}
 */
export function validateSocialCreditCode(Code) {
  const patrn = /^[0-9A-Z]+$/
  //18位校验及大写校验
  if ((Code.length !== 18) || (patrn.test(Code) === false)) {
    console.info('不是有效的统一社会信用编码！')
    return false
  } else {
    let Ancode//统一社会信用代码的每一个值
    let Ancodevalue//统一社会信用代码每一个值的权重
    let total = 0
    const weightedfactors = [1, 3, 9, 27, 19, 26, 16, 17, 20, 29, 25, 13, 8, 24, 10, 30, 28]//加权因子
    const str = '0123456789ABCDEFGHJKLMNPQRTUWXY'
    //不用I、O、S、V、Z
    for (let i = 0; i < Code.length - 1; i++) {
      Ancode = Code.substring(i, i + 1)
      Ancodevalue = str.indexOf(Ancode)
      total = total + Ancodevalue * weightedfactors[i]
      //权重与加权因子相乘之和
    }
    let logiccheckcode = 31 - total % 31
    if (logiccheckcode == 31) {
      logiccheckcode = 0
    }
    const Str = '0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,J,K,L,M,N,P,Q,R,T,U,W,X,Y'
    const Array_Str = Str.split(',')
    logiccheckcode = Array_Str[logiccheckcode]


    const checkcode = Code.substring(17, 18)
    if (logiccheckcode != checkcode) {
      console.info('不是有效的统一社会信用编码！')
      return false
    } else {
      return true
    }
    return true
  }
}

/**
 * 判断手机号码是否正确
 */
export function isvalidatemobile(phone) {
  const list = []
  let result = true
  let msg = ''
  const isPhone = /^0\d{2,3}-?\d{7,8}$/
  // 增加134 减少|1349[0-9]{7}，增加181,增加145，增加17[678]
  if (!validatenull(phone)) {
    if (phone.length === 11) {
      if (isPhone.test(phone)) {
        msg = '手机号码格式不正确'
      } else {
        result = false
      }
    } else {
      msg = '手机号码长度不为11位'
    }
  } else {
    msg = '手机号码不能为空'
  }
  list.push(result)
  list.push(msg)
  return list
}

/**
 * 判断手机号码是否正确（可以为空）
 */
export function isValidateNoneMobile(phone) {
  const list = []
  let result = true
  let msg = ''
  const isPhone = /^0\d{2,3}-?\d{7,8}$/
  // 增加134 减少|1349[0-9]{7}，增加181,增加145，增加17[678]
  if (!validatenull(phone)) {
    if (phone.length === 11) {
      if (isPhone.test(phone)) {
        msg = '手机号码格式不正确'
      } else {
        result = false
      }
    } else {
      msg = '手机号码长度不为11位'
    }
  } else {
    result = false
  }
  list.push(result)
  list.push(msg)
  return list
}

/**
 * 判断姓名是否正确
 */
export function validatename(name) {
  const regName = /^[\u4e00-\u9fa5]{2,4}$/
  if (!regName.test(name)) return false
  return true
}

/**
 * 判断是否为整数
 */
export function validatenum(num, type) {
  let regName = /[^\d.]/g
  if (type === 1) {
    if (!regName.test(num)) return false
  } else if (type === 2) {
    regName = /[^\d]/g
    if (!regName.test(num)) return false
  }
  return true
}

/**
 * 判断是否为小数
 */
export function validatenumord(num, type) {
  let regName = /[^\d.]/g
  if (type === 1) {
    if (!regName.test(num)) return false
  } else if (type === 2) {
    regName = /[^\d.]/g
    if (!regName.test(num)) return false
  }
  return true
}

/**
 * 判断是否为空
 */
export function validatenull(val) {
  if (typeof val === 'boolean') {
    return false
  }
  if (typeof val === 'number') {
    return false
  }
  if (val instanceof Array) {
    if (val.length === 0) return true
  } else if (val instanceof Object) {
    //if (JSON.stringify(val) === '{}') return true
    return Object.keys(val).length === 0
  } else {
    if (val === 'null' || val == null || val === 'undefined' || val === undefined || val === '') return true
    return false
  }
  return false
}

export function containsEnSpecial(val) {
  const containSpecial = RegExp(
    /[(\ )(\~)(\!)(\@)(\#)(\$)(\%)(\^)(\&)(\*)(\()(\))(\-)(\+)(\=)(\[)(\])(\{)(\})(\|)(\\)(\;)(\:)(\')(\")(\,)(\.)(\/)(\<)(\>)(\?)(\)]+/
  )
  return containSpecial.test(val)
}
export function containsZhSpecial(val) {
  if (val.indexOf('·') > -1) {
    return true
  }
  const reg = /[\u3002|\uff1f|\uff01|\uff0c|\u3001|\uff1b|\uff1a|\u201c|\u201d|\u2018|\u2019|\uff08|\uff09|\u300a|\u300b|\u3008|\u3009|\u3010|\u3011|\u300e|\u300f|\u300c|\u300d|\ufe43|\ufe44|\u3014|\u3015|\u2026|\u2014|\uff5e|\ufe4f|\uffe5]/
  return reg.test(val)
}
export function isLetterNumber(val) {
  const reg = /^[A-Za-z0-9]*$/
  return reg.test(val)
}
export function isNumber(val) {
  const reg = /^[0-9]*$/
  return reg.test(val)
}
export function filterSpecialChar(val) {
  if (validatenull(val)) {
    return val
  }
  return val.replace(/[^\a-\z\A-\Z0-9\u4E00-\u9FA5\-\#]/g, '')
}
